'''
Author: cw
Date: 2025-08-15
Description: 创建作图任务，获取作图结果
'''
import json

from fapi import env

from utils import http_util
from modules.wx_api_mgr import WxApiMgr
from modules import image_task_mgr, app_mgr
from modules.image_task_mgr import TaskStatus


async def create(prompt: str, appid: str, openid: str):
    """作图"""
    url = f"{env.IMAGE_HOST}/api/tasks"
    data = {
        "biz": "mp",
        "title": "公众号作图",
        "desc": prompt,
        "count": 1,
        "cb": "https://mp.jbdhm.icu/event",
        "user_id": openid
    }
    res = await http_util.aio_post(url, json=data, timeout=10)
    if not res:
        raise Exception("创建作图失败")
    return res


async def get_task(task_id: str):
    """获取作图结果"""
    url = f"{env.IMAGE_HOST}/api/tasks/{task_id}"
    res = await http_util.aio_get(url, timeout=10)
    if not res:
        raise Exception("获取作图结果失败")
    return res


async def task_cb(result: dict):
    """作图回调"""
    # 更新制作状态
    task_id = str(result['task_id'])
    status = TaskStatus.SUCCESSED.name
    if result.get("error_msg"):
        status = TaskStatus.FAILED.name

    task = await image_task_mgr.update_by_work_id(
        work_id=task_id,
        update_data={
            'status': status,
            'detail': result
        },
    )

    # app
    appid = task.get('appid')
    app_info = await app_mgr.get_info_by_appid(appid)
    if not app_info:
        raise Exception(f"未注册，appid={appid}")

    # token
    wxapi = WxApiMgr(
        appid=appid,
        secret=app_info.get('secret_id'),
    )

    # 置换media_id
    image = result.get('image')
    if not image:
        raise Exception(f"作图失败，msg={result}")
    first_image_url = image[0]
    image_data = await http_util.aio_get(first_image_url, fmt='bin', timeout=15)
    res = await wxapi.get_temp_media(image_data)
    res = json.loads(res)
    if not(res and res.get("media_id")):
        raise Exception(f"置换media_id失败，res={res}")

    # 发送消息
    send_res = await wxapi.message_custom(
        openid=task.get('openid'),
        msg_type='image',
        image = {
            "media_id": res.get('media_id')
        }
    )
    # 更新
    detail = {**task.get('detail'), 'media_id': res.get('media_id')}
    task = await image_task_mgr.update_by_work_id(
        work_id=task_id,
        update_data={
            'send_res': send_res,
            'detail': detail
        }
    )
    return {"status": "OK"}
